import type { Ref } from "vue";
import { unref, nextTick } from "vue";
import { useDebounceFn, useEventListener, useTimeoutFn, tryOnUnmounted } from "@vueuse/core";
import type { EChartsOption } from "echarts";
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from "echarts/core";
/** 引入柱状图and折线图图表，图表后缀都为 Chart  */
import { BarChart } from "echarts/charts";
// 引入提示框，标题，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from "echarts/components";
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from "echarts/features";
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from "echarts/renderers";
import theme from "./json/theme.json";
// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);
echarts.registerTheme("vintage", theme);
// 导出
export default function useEcharts(elRef: Ref<HTMLDivElement>) {
  // 实例化对象
  let chartInstance: echarts.ECharts | null = null;
  // 页面尺寸变化
  let resizeFn: any = resize;
  resizeFn = useDebounceFn(resize, 200);
  // 移除监听事件
  let removeResizeFn = () => {};

  // 初始化
  function initCharts() {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }
    chartInstance = echarts.init(el, "vintage");
    // 添加页面尺寸变化监听事件
    removeResizeFn = useEventListener(window, "resize", resizeFn);
  }
  // 尺寸变化
  function resize() {
    chartInstance!.resize({
      animation: {
        duration: 300,
        easing: "quadraticIn"
      }
    });
  }
  // 实例化对象
  function getInstance(): echarts.ECharts | null {
    if (!chartInstance) {
      initCharts();
    }
    return chartInstance;
  }
  // 设置内容
  function setOptions(options: EChartsOption, isMerge = true) {
    return new Promise((resolve) => {
      nextTick(() => {
        useTimeoutFn(() => {
          if (!chartInstance) {
            initCharts();
          }
          chartInstance?.clear();
          chartInstance?.setOption(options, isMerge); // 第二个参数为true表示合并而不是替换
          resolve(null);
        }, 300);
      });
    });
  }
  // 组件销毁之前
  tryOnUnmounted(() => {
    if (!chartInstance) return;
    removeResizeFn();
    chartInstance.dispose(); // 清理释放资源
    chartInstance = null;
  });

  return {
    echarts,
    resize,
    getInstance,
    setOptions
  };
}
